using System;
using System.IO;
using System.Threading;

namespace InfiniTec.IO
{
	internal sealed class MemoryMappedFileStreamSharedState
	{
		private readonly Stream _Owner;
		public MemoryMappedFileSafeHandle Handle { get; private set; }
		public long Capacity { get; private set; }
		public FileStream UnderlyingStream { get; private set; }
		public long Length { get; private set; }

		private int _ReferenceCounter;

		public MemoryMappedFileStreamSharedState(MemoryMappedFileSafeHandle handle, long length, long capacity, FileStream underlyingStream, Stream owner)
		{
			Handle = handle;
			Length = length;
			Capacity = capacity;
			UnderlyingStream = underlyingStream;
			_Owner = owner;
		}

		public void SetLength(long length, Stream owner)
		{
			if (owner != _Owner)
			{
				throw new ArgumentException("The length can only be modified by the owner.");
			}
			Length = length;
		}

		public void SetCapacity(long capacity, Stream owner)
		{
			if (owner != _Owner)
			{
				throw new ArgumentException("The length can only be modified by the owner.");
			}
			Capacity = capacity;
		}
		public void AddReference()
		{
			Interlocked.Increment(ref _ReferenceCounter);
		}

		public void RemoveReference()
		{
			if (Interlocked.Decrement(ref _ReferenceCounter) != 0) return;

			Handle.Dispose();

			if (UnderlyingStream != null)
			{
				UnderlyingStream.Dispose();
			}
		}


	}
}